import React from 'react';
import ReactDOM from 'react-dom';
import { List, Toast, Button, Flex, Slider } from 'antd-mobile';
import mirror, { actions, connect } from 'mirrorx';
import { getCertiTypeEnglish, getGenderEnglish, getRelationEnglish, getSA, getCoveragePeriod, getPaymentPeriod, getPayMode, getBenefitPeriod, getSocialInsurance } from './staticData';
import { createForm } from 'rc-form';
import RowInput from '../../component/Item/Input';
import RowSelect from '../../component/Item/Select';
import RowDate from '../../component/Item/DatePicker';
import Factor from '../../component/factor';
import Job from './job';
import RiskNotice from './riskNotice';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            applicantInfo: {
                applicantCertType: 'SHENFENZHENG',
            },  // 投保人信息
            insurantInfo: {
                insurantCertType: 'SHENFENZHENG',
                insurance: "YES"
            },   // 被保人信息
            factorInfo: {
            },     // 保费试算因子信息
            premium: '', // 输入框保费
            amount: '', // 保额
            sum: { premiumTotal: '', sumTotal: '', topup: '' },
            percent: 50

        };
    }

    componentDidMount() {
        let Insure = JSON.parse(sessionStorage.getItem('Insure'));
        if (Insure) {
            this.setState({ applicantInfo: Insure })
        }
    }

    onChangeApplicant = (obj) => {
        if (obj.hasOwnProperty('applicantCertNo')) {
            var a = this.isIdCard(Object.values(obj)[0])
            if (Object.prototype.toString.call(a) == "[object Object]") {
                Object.assign(this.state.applicantInfo, {
                    applicantBirthday: new Date(a.birthday).getTime(),
                    applicantGender: a.genderCode
                })
                this.setState({ applicantInfo: this.state.applicantInfo })
            }
        }
        Object.assign(this.state.applicantInfo, obj)
        this.setState({ applicantInfo: this.state.applicantInfo })
    }

    onChangeInsurant = (obj) => {
        if (obj.relation == 'SELF') {
            const { applicantName, applicantCertType, applicantCertNo, applicantBirthday,
                applicantGender, applicantMobile, applicantEmail } = this.state.applicantInfo;
            Object.assign(this.state.insurantInfo, {
                insurantName: applicantName,
                insurantCertType: applicantCertType,
                insurantCertNo: applicantCertNo,
                insurantBirthday: applicantBirthday,
                insurantGender: applicantGender,
                insurantMobile: applicantMobile,
                insurantEmail: applicantEmail,
            })
        }
        if (obj.hasOwnProperty('insurantCertNo')) {
            var a = this.isIdCard(Object.values(obj)[0])
            if (Object.prototype.toString.call(a) == "[object Object]") {
                Object.assign(this.state.insurantInfo, {
                    insurantBirthday: new Date(a.birthday).getTime(),
                    insurantGender: a.genderCode
                })
            }
        }
        Object.assign(this.state.insurantInfo, obj)
        this.setState({ insurantInfo: this.state.insurantInfo })
    }

    onChangePremium = (obj) => {
        this.setState(obj)
    }

    onChangeRiskNotice = (obj) => {
        this.setState(obj)
    }

    isIdCard = (card) => {
        if (!card) return true;
        var num = card.toUpperCase();
        //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
        if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
            return false;
        }
        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
        //下面分别分析出生日期和校验位
        var len, re;
        var birthday, genderCode;
        len = num.length;
        if (len == 15) {

            //获取出生日期
            birthday = '19' + card.substring(6, 8) + "-" + card.substring(8, 10) + "-" + card.substring(10, 12);
            //获取性别
            genderCode = parseInt(card.substr(14, 1)) % 2 == 1 ? 'MALE' : 'FMAIL';

            re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
            var arrSplit = num.match(re);

            //检查生日日期是否正确
            var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
                return false;
            } else {
                //将15位身份证转成18位
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                var valnum;
                var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                var nTemp = 0,
                    i;

                num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
                for (i = 0; i < 17; i++) {
                    nTemp += num.substr(i, 1) * arrInt[i];
                }
                num += arrCh[nTemp % 11];
            }
        } else if (len == 18) {

            //获取出生日期
            birthday = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14);
            //获取性别
            genderCode = parseInt(card.substr(16, 1)) % 2 == 1 ? 'MALE' : 'FMAIL';

            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var arrSplit = num.match(re);

            //检查生日日期是否正确
            var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
                return false;
            } else {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                var valnum;
                var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                var nTemp = 0,
                    i;
                for (i = 0; i < 17; i++) {
                    nTemp += num.substr(i, 1) * arrInt[i];
                }
                valnum = arrCh[nTemp % 11];
                if (valnum != num.substr(17, 1)) {
                    return false;
                }
            }
        }
        return {
            birthday: birthday,
            genderCode: genderCode
        }
    }

    submitAction = () => {
        sessionStorage.setItem("Insure", JSON.stringify(this.state.applicantInfo));
          let listInvestments = [
            {
                "sumInsured": this.state.protectionSum,
                "investType": "Protection",
                "investAmount": this.state.protectionPremium,
                "times": this.state.protectionSum / this.state.protectionPremium 
            }, {
                "sumInsured": this.state.savingSum,
                "investType": "Saving",
                "investAmount": this.state.savingPremium,
                "times": 5
            }           
        ]
        if(this.state.sum.topup){
             listInvestments.push( {
                "investAmount": this.state.sum.topup,
                "investType": "SingleTopUp"
            })
        }
        let param = {
            ...this.state.applicantInfo,
            ensurePersons: [{
                ...this.state.insurantInfo,
                ensurePlanId: T.urlQuery('planId'),
                insurantPremium: this.state.sum.premiumTotal,
                listInvestments:listInvestments
            }],
            goodsId: T.urlQuery('goodId'),
            campaignId: T.urlQuery('campaignId'),
            productSumInsurant: this.state.sum.sumTotal
        };
        param.applicantMobile = param.applicantMobile && param.applicantMobile.replace(/ /g, "");
        param.ensurePersons[0].insurantMobile = param.ensurePersons[0].insurantMobile && param.ensurePersons[0].insurantMobile.replace(/ /g, "");

      
        param.amount = this.state.premium

        console.log('param', param)
        if (T.urlQuery('goodId') == '10') {
            // param.ensurePersons[0].insurance = this.state.factorInfo.socialInsurance;
        }
        if (!this.state.showRiskNotice) {
            T.showError("Plear Agree Notice Of Insurance And Clauses Of Insurance");
        } else if (this.state.premium < 10000) {
            T.showError("The premium shall not be less than 10000");
        } else {
            this.requestSubmit(param)
        }

    }

    requestSubmit = (param) => {
        let topup = 0;
        if(this.state.sum.topup){
            topup = this.state.sum.topup;
        }
        T.fetch({
            url: '/order/submit.json',
            loading: true,
            data: param
        }).then((res) => {
            if (res.success) {
                console.log("res", res)
                actions.routing.push({
                    pathname: 'pay',
                    search: `?id=${res.value.orderNo}&topup=${topup}`
                })
            }
        })
    }

    // 保费算保额
    requestAmountCal = (value) => {
        T.fetch({
            url: '/cal/amountCal.json',
            loading: true,
            data: {
                "bizTopic": "INSURED",
                "id": T.urlQuery('planId'),
                "factorParams": value
            }
        }).then((res) => {
            if (res.success) {
                this.setState({ amount: res.value.calValue })
            }
        })
    }

    onBlurPremium = (value) => {
        this.requestAmountCal(value)
    }

    onChangeSum = (obj) => {
        Object.assign(this.state.sum, obj)
        this.setState({ sum: this.state.sum })
    }
    scrollChange = (value) => {
        setTimeout(() => {
            this.setState({
                percent: value
            })
        }, 0);
        this.calSum(value);
    }

    calSum = (value) => {
        const sum = this.state.sum; //premiumTotal sumTotal
        const percent = value / 100;
        let protectionPremium = Math.round(percent * sum.premiumTotal);
        let savingPremium = sum.premiumTotal - protectionPremium;
        let savingSum = savingPremium * 5;
        let protectionSum = sum.sumTotal - savingSum;
        setTimeout(() => {
            this.setState({
                protectionPremium: protectionPremium,
                savingPremium: savingPremium,
                savingSum: savingSum,
                protectionSum: protectionSum
            })
        }, 0);
        if (protectionSum <= 0) {
            T.showError("Protection SA must be large than 0");
        }
    }
    onBlurSum = () => {
        const value = this.state.percent;
        if (this.state.sum.sumTotal){
            this.calSum(value);
        }
        this.getAmount();
    }

    getAmount = () => {
        let topup = 0;
        if(this.state.sum.topup){
            topup = this.state.sum.topup;
        }
        const amount = Number(this.state.sum.premiumTotal) + Number(topup);
        this.setState({ premium: amount })
    }

    render() {
        let { applicantInfo, insurantInfo, factorInfo, goodId, premium, sum, test } = this.state;
        console.log(this.state)
        return (
            <div className="insure">
                <div className="title">Policyholder Info</div>
                <div>
                    <List>
                        <RowInput label="Name" name="applicantName" language='English' value={applicantInfo.applicantName} callback={this.onChangeApplicant} />
                        <RowSelect label="ID Type" name="applicantCertType" language='English' value={applicantInfo.applicantCertType} data={getCertiTypeEnglish()} callback={this.onChangeApplicant} />
                        <RowInput label="ID Number" name="applicantCertNo" language='English' value={applicantInfo.applicantCertNo} callback={this.onChangeApplicant} />
                        <RowDate label="Birthdate" name="applicantBirthday" language='English' value={applicantInfo.applicantBirthday} callback={this.onChangeApplicant} />
                        <RowSelect label="Gender" name="applicantGender" language='English' value={applicantInfo.applicantGender} data={getGenderEnglish()} callback={this.onChangeApplicant} />
                        <RowInput label="Phone Number" type="phone" name="applicantMobile" language='English' value={applicantInfo.applicantMobile} callback={this.onChangeApplicant} />
                        <RowInput label="E-mail" name="applicantEmail" language='English' value={applicantInfo.applicantEmail} callback={this.onChangeApplicant} />
                    </List>
                </div>
                <div className="title">Life Assured Info</div>
                <div>
                    <List>
                        <RowSelect label="For Whom" name="relation" language='English' value={insurantInfo.relation} data={getRelationEnglish()} callback={this.onChangeInsurant} />
                        <RowInput label="Name" name="insurantName" language='English' value={insurantInfo.insurantName} callback={this.onChangeInsurant} />
                        <RowSelect label="ID Type" name="insurantCertType" language='English' value={insurantInfo.insurantCertType} data={getCertiTypeEnglish()} callback={this.onChangeInsurant} />
                        <RowInput label="ID Number" name="insurantCertNo" language='English' value={insurantInfo.insurantCertNo} callback={this.onChangeInsurant} />
                        <RowDate label="Birthdate" name="insurantBirthday" language='English' value={insurantInfo.insurantBirthday} callback={this.onChangeInsurant} />
                        <RowSelect label="Gender" name="insurantGender" language='English' value={insurantInfo.insurantGender} data={getGenderEnglish()} callback={this.onChangeInsurant} />
                        <RowInput label="Phone Number" type="phone" name="insurantMobile" language='English' value={insurantInfo.insurantMobile} callback={this.onChangeInsurant} />
                        <RowInput label="E-mail" name="insurantEmail" language='English' value={insurantInfo.insurantEmail} callback={this.onChangeInsurant} />
                        <RowSelect label="Social Insurance" name="insurance" language='English' value={insurantInfo.insurance} data={getSocialInsurance()} callback={this.onChangeInsurant} />
                    </List>
                </div>

                <div className="title">Premium Info</div>
                <div>
                    <List>
                        <RowInput label="Premium" name="premiumTotal" language='English' value={sum.premiumTotal} callback={this.onChangeSum} onBlur={this.onBlurSum} />
                        <RowInput label="Sum Assured" name="sumTotal" language='English' value={sum.sumTotal} callback={this.onChangeSum} onBlur={this.onBlurSum} />
                    </List>
                </div>
                <div style={{ paddingTop: 20, paddingBottom: 20, position: "relative" }}>
                    <div style={{ color: "#fff", position: "absolute", left: 4, top: 20, zIndex: "10" }}>Protection Part</div>
                    <div style={{ color: "#fff", position: "absolute", right: 4, top: 20, zIndex: "10" }}>Saving Part</div>
                    {/*<div style={{color:"#000",position:"absolute",right:"50%",top:10,zIndex:"10"}}>{this.state.percent}%</div>*/}
                    <Slider
                        style={{ width: "100%" }}
                        defaultValue={50}
                        min={0}
                        max={100}
                        step={1}
                        onChange={this.scrollChange}
                        trackStyle={{
                            backgroundColor: '#10c286',
                            height: '20px',
                        }}
                        railStyle={{
                            backgroundColor: '#1890FF',
                            height: '20px',
                        }}
                        handleStyle={{
                            borderColor: '#1890FF',
                            height: '30px',
                            width: '30px',
                            marginLeft: '-15px',
                            marginTop: '-4.5px',
                            backgroundColor: '#1890FF',
                            zIndex: 99,
                            opacity: 0.8
                        }}
                    />
                </div>

                <div className="title tal pl30" style={{ background: "#fff" }}>Protection Part</div>
                <div>
                    <List>
                        <Flex>
                            <RowInput label="Premium" name="premiumProtection" editable={false} language='English' value={this.state.protectionPremium} callback={this.onChangeSum} />
                            <RowInput label="Sum Assured" name="sumProtection" editable={false} language='English' value={this.state.protectionSum} callback={this.onChangeSum} />
                        </Flex>
                    </List>
                </div>

                <div className="title tal pl30" style={{ background: "#fff" }}>Saving Part</div>
                <div>
                    <List>
                        <Flex>
                            <RowInput label="Premium" name="premiumSaving" editable={false} language='English' value={this.state.savingPremium} callback={this.onChangeSum} />
                            <RowInput label="Sum Assured" name="sumSaving" editable={false} language='English' value={this.state.savingSum} callback={this.onChangeSum} />
                        </Flex>
                    </List>
                </div>

                <div className="title">Top Up Info</div>
                <div>
                    <List>
                        <RowInput label="Top Up" required={false} name="topup" language='English' value={sum.topup} callback={this.onChangeSum} onBlur={this.getAmount} />
                    </List>
                </div>

                <RiskNotice callback={this.onChangeRiskNotice} language='English' goodId={T.urlQuery('goodId')} />
                <div className="footer">
                    <div className="footer-left">
                        <a className="f38 fc6 tac color-price">&nbsp;&nbsp;<span className="f30"></span><span id="totalMoney">${this.state.premium || 0}</span></a>
                    </div>
                    <div className="footer-right">
                        <a href="javascript:;" className="f32 fcw diy_background" id="applyBtn" onClick={this.submitAction}>Confirm</a>
                    </div>
                </div>
            </div>
        )
    }
}

export default App;